#include "RefDesParser.h"

#include "BoolParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

RefDesParser::RefDesParser(
    QStringParser *&_nameParser
    , QStringParser *&_packageRefParser
    , BoolParser *&_populateParser
    , QStringParser *&_layerRefParser
):    m_nameParser(_nameParser)
    , m_packageRefParser(_packageRefParser)
    , m_populateParser(_populateParser)
    , m_layerRefParser(_layerRefParser)
{

}

bool RefDesParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new RefDes());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("name")))
    {
        data = reader->attributes().value(QStringLiteral("name"));
        if (!m_nameParser->parse(reader, data))
            return false;
        m_result->name = m_nameParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("name: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("packageRef")))
    {
        data = reader->attributes().value(QStringLiteral("packageRef"));
        if (!m_packageRefParser->parse(reader, data))
            return false;
        m_result->packageRefOptional = Optional<QString>(m_packageRefParser->result());
    }
    if (reader->attributes().hasAttribute(QStringLiteral("populate")))
    {
        data = reader->attributes().value(QStringLiteral("populate"));
        if (!m_populateParser->parse(reader, data))
            return false;
        m_result->populateOptional = Optional<Bool>(m_populateParser->result());
    }
    if (reader->attributes().hasAttribute(QStringLiteral("layerRef")))
    {
        data = reader->attributes().value(QStringLiteral("layerRef"));
        if (!m_layerRefParser->parse(reader, data))
            return false;
        m_result->layerRef = m_layerRefParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("layerRef: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

RefDes *RefDesParser::result()
{
    return m_result.take();
}

}